<template>
  <div class="content-detail list-page">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="填写-施工质量检查"
          @back="handleBack"
        ></el-page-header>
      </div>
    </el-card>

    <el-card class="card-box">
      <el-descriptions
        :column="3"
        size="large"
        title="基础信息"
        class="descriptions"
      >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="单据名称"
          >{{ checkInfoData.monomerName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="工程类型"
          >{{ checkInfoData.atypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="分部"
          >{{ checkInfoData.btypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="子分部"
          >{{ checkInfoData.ctypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="分项"
          >{{ checkInfoData.dtypeName }}</el-descriptions-item
        >
      </el-descriptions>
    </el-card>

    <el-card class="card-box card-table">
      <template #header>
        <div class="card-box-header">
          <div class="card-header">检查项列表</div>
          <div class="card-action" v-auth="`/projectsS/quality--add`">
            <el-button type="primary" @click="handleAddCheck">新增</el-button>
            <el-button type="primary" @click="handleDeleteBatch"
              >删除</el-button
            >
          </div>
        </div>
      </template>

      <el-skeleton
        style="height: calc(100vh - 400px)"
        :rows="8"
        :loading="loading"
        animated
      ></el-skeleton>
      <el-table
        :border="false"
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="loading"
        v-if="!loading"
        :header-cell-style="{
          background: '#F7F9FD',
          color: '#000',
          height: '48px'
        }"
        :height="'calc(100vh - 500px)'"
        @selection-change="handleSelectionChange"
        :row-key="getRowKeys"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          :selectable="selectable"
          width="55"
        />
        <template #empty>
          <el-empty :image-size="150" description="暂无数据"></el-empty>
        </template>

        <el-table-column type="index" label="序号" width="80">
          <template v-slot="scope">
            <span>{{
              (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="检查内容"> </el-table-column>
        <el-table-column prop="requests" label="标准要求"> </el-table-column>
        <el-table-column prop="checkMethod" label="检查方法"></el-table-column>
        <el-table-column prop="createTime" label="已完成/已检查">
          <template #default="{ row }">
            <span class="times" @click="handleList(row)"
              >{{ row.insFinishTimes }}/{{ row.insTimes }}</span
            >
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <el-button
              class="add"
              type="text"
              size="small"
              @click="handleAdd(row)"
              v-auth="`/projectsS/quality--add`"
              >新建</el-button
            >
            <el-button
              class="add"
              type="text"
              size="small"
              @click="handleDelete(row)"
              v-auth="`/projectsS/quality--add`"
              v-if="
                Number(row.insFinishTimes) === 0 && Number(row.insTimes) === 0
              "
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="showAddCheck"
      title="新建检查反馈"
      width="38vw"
      destroy-on-close
      custom-class="add-check"
    >
      <add-check-feed-back
        :checkItem="checkItem"
        ref="formRef"
      ></add-check-feed-back>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddCheck = false">取消</el-button>
          <el-button
            :loading="showAddCheckFeedBackSaveLoading"
            type="primary"
            @click="handleSure"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showCheckList"
      title="检查列表"
      width="70%"
      destroy-on-close
      custom-class="check-list"
    >
      <check-list :checkItem="checkItem" @closeList="closeList"></check-list>
    </el-dialog>

    <!-- 检查详情 -->
    <el-dialog
      v-model="showCheckDetail"
      title="检查详情（安全技术交底）"
      width="70%"
      destroy-on-close
      custom-class="check-list check-color"
    >
      <check-detail
        @closeDetail="closeDetail"
        :instanceId="instanceId"
      ></check-detail>
    </el-dialog>
    <!-- 新增检查项 -->
    <el-dialog
      v-model="showAddCheckList"
      title="新增列表"
      width="70%"
      destroy-on-close
      custom-class="check-list"
      @closed="closeAddList"
    >
      <add-check-list :checkItem="checkItem"></add-check-list>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { useRoute, useRouter } from "vue-router";
import { defineComponent, reactive, ref } from "vue";
import NotifMessage from "/@/utils/message/notification";
import addCheckFeedBack from "../components/addCheckFeedBack.vue";
import checkList from "../components/checkList.vue";
import addCheckList from "../components/addCheckList.vue";
import checkDetail from "../components/checkDetail.vue";
import {
  checkInfo,
  checkItemList,
  addCheckRecord,
  flowStart,
  checkItemListDeleteBatch
} from "/@/api/construction";
import { storageLocal } from "/@/utils/storage";
import { clickEvent } from "/@/utils/func";
import { onFilterFileData } from "/@/utils/file";
export default defineComponent({
  name: "fill",
  components: { addCheckFeedBack, checkList, checkDetail, addCheckList },
  setup() {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const router = useRouter();
    const route = useRoute();
    let tableData = ref([]);
    let checkInfoData = ref({});
    let selectSet = ref([]);
    let checkId = route.query.id;
    const instanceId = ref();
    const checkItem = ref({});
    const showAddCheck = ref<boolean>(false);
    const showAddCheckFeedBackSaveLoading = ref<boolean>(false);
    const showCheckList = ref<boolean>(false);
    const showCheckDetail = ref<boolean>(false);
    const showAddCheckList = ref<boolean>(false);
    const loading = ref<boolean>(false);
    const pageState = reactive({
      pageNum: 1,
      pageSize: 500
    });

    //发起流程
    const flowStartData = reactive({
      formBaseInfo: {
        billName: "",
        projectName: storageLocal.getItem("projectInfo").name,
        projectManageId: storageLocal.getItem("projectInfo").id,
        id: ""
      },
      flowFormData: {
        approvalResult: "不合格",
        businessId: "",
        flowTypeCode: "1015",
        nodeId: "ACT_010",
        projectManageId: storageLocal.getItem("projectInfo").id
      },
      formSubMap: {
        flowType: "1015",
        assignee: null,
        opinion: ""
      }
    });
    // 获取检查项列表
    async function getCheckItemList() {
      try {
        loading.value = true;
        let postData = { qtyCheckId: +checkId, isShow: 1 };
        const { code, data } = await checkItemList({
          ...pageState,
          ...postData
        });
        if (code === 200) {
          tableData.value = data?.list;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }

    // 获取工程质量详情
    const checkDetail = async () => {
      try {
        let postData = { id: checkId };
        const { code, data } = await checkInfo(postData);
        if (code === 200) {
          checkInfoData.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    //新增检查记录
    const handleSure = async () => {
      const isValid = await formRef.value.validate();
      if (!isValid) return;
      const params = await formRef.value.formData;
      const fileList = await formRef.value.formData;
      params.partybHandlerId = params?.partybHandlerInfo?.value;
      params.partybHandlerName = params?.partybHandlerInfo?.label;
      params.jpysAttachmentArr = onFilterFileData(fileList.jpysAttachment);
      params.kzxmclAttachmentArr = onFilterFileData(fileList.kzxmclAttachment);
      params.ysrymdAttachmentArr = onFilterFileData(fileList.ysrymdAttachment);
      params.ysryzpAttachmentArr = onFilterFileData(fileList.ysryzpAttachment);
      params.handlerType = 1;
      if (params.isQualifiedCheck === "1") {
        //合格
        params.approveStatus = 2;
      } else if (params.isQualifiedCheck == "0") {
        //不合格
        params.approveStatus = 1;
      }
      try {
        showAddCheckFeedBackSaveLoading.value = true;
        const { code, data, message } = await addCheckRecord(params);
        if (code === 200) {
          clickEvent("填写-施工质量检查", "新建", "新建检查反馈");
          checkFlowStart(data, params, fileList);
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    //发起流程
    const checkFlowStart = async (data, params, fileList) => {
      flowStartData.formBaseInfo.billName = `${checkInfoData.value.monomerName}_[${checkItem.value.content}]的审批流程`;
      flowStartData.formBaseInfo.id = data;
      flowStartData.flowFormData.businessId = data;
      flowStartData.formSubMap.assignee = params.partybHandlerId;
      flowStartData.formSubMap.opinion = JSON.stringify([
        {
          name: "是否合格",
          content: params.isQualifiedCheck === "1" ? "合格" : "不合格",
          code: params.isQualifiedCheck,
          type: "radio"
        },
        { name: "检查小结", content: params.insSummary, type: "textarea" },
        {
          name: "主要控制点照片(测量、现状、近景等)",
          content: fileList.kzxmclAttachment,
          type: "images"
        },
        {
          name: "举牌验收照片",
          content: fileList.jpysAttachment,
          type: "images"
        },
        {
          name: "验收人员名单",
          content: fileList.ysrymdAttachment,
          type: "images"
        },
        {
          name: "验收人员照片",
          content: fileList.ysryzpAttachment,
          type: "images"
        }
      ]);
      try {
        const { code, message } = await flowStart(flowStartData);
        if (code === 200) {
          clickEvent(
            "填写-施工质量检查",
            "保存",
            `流程发起_${checkInfoData.value.monomerName}_[${checkItem.value.content}]`
          );
          getCheckItemList();
          showAddCheck.value = false;
          NotifMessage.success(message);
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
      showAddCheckFeedBackSaveLoading.value = false;
    };

    const handleAdd = row => {
      checkItem.value = row;
      showAddCheck.value = true;
    };
    const handleDelete = async row => {
      try {
        loading.value = true;
        const res = await checkItemListDeleteBatch({
          ids: [row.id]
        });
        if (res.code === 200) {
          getCheckItemList();
          NotifMessage.success("删除成功");
        }
      } catch (err) {
        loading.value = false;
      }
    };
    const handleDeleteBatch = async () => {
      try {
        if (selectSet.value.length === 0) {
          NotifMessage.error("请选择要删除的数据");
          return;
        }
        loading.value = true;
        const res = await checkItemListDeleteBatch({
          ids: selectSet.value
        });
        if (res.code === 200) {
          getCheckItemList();
          NotifMessage.success("删除成功");
          selectSet.value = [];
        }
      } catch (error) {
        loading.value = false;
      }
    };
    const handleAddCheck = () => {
      showAddCheckList.value = true;
    };
    const handleList = row => {
      checkItem.value = row;
      showCheckList.value = true;
    };

    // 返回按钮事件
    const handleBack = () => {
      router.push("/projectsS/construction/quality");
    };

    const closeList = type => {
      showCheckDetail.value = true;
      instanceId.value = type;
    };
    const closeDetail = () => {
      showCheckDetail.value = false;
    };
    const closeAddList = () => {
      getCheckItemList();
    };
    const getRowKeys = row => {
      return row.id;
    };
    const handleSelectionChange = val => {
      selectSet.value = val.map(item => item.id);
    };
    const selectable = row => {
      return Number(row.insFinishTimes) === 0 && Number(row.insTimes) === 0;
    };

    if (checkId) {
      checkDetail();
      getCheckItemList();
    }

    return {
      formRef,
      tableData,
      handleBack,
      showAddCheck,
      showCheckList,
      showCheckDetail,
      showAddCheckList,
      checkInfoData,
      pageState,
      loading,
      handleAdd,
      handleList,
      checkItem,
      handleSure,
      closeList,
      closeDetail,
      instanceId,
      handleAddCheck,
      closeAddList,
      getRowKeys,
      handleSelectionChange,
      handleDelete,
      handleDeleteBatch,
      selectable,
      showAddCheckFeedBackSaveLoading
    };
  }
});
</script>

<style lang="scss" scoped>
.descriptions {
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #494c53;

  :deep .el-descriptions__header {
    padding: 14px 0 14px 16px;
    border-bottom: 1px solid #c2cade;
  }

  :deep .my-content {
    min-width: 200px;
    padding: 6px 0 6px 12px;
    background: #fdfdff;
    border-radius: 4px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #8895b7;
    font-size: 14px;
    display: inline-block;
  }
}

.card-table {
  height: calc(100% - 48px - 180px);
  .card-box-header {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .card-action {
      margin: 0 0 0 10px;
    }
  }
  .card-header {
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: bold;
    color: #494c53;
  }

  :deep .el-card__body {
    height: calc(100% - 50px);
    padding: 16px !important;

    .times {
      color: #5298ff;
      cursor: pointer;
    }
  }
}

:deep .add-check {
  .el-dialog__body {
    padding: 22px 36px 8px 36px;
  }
}

:deep .check-list {
  .el-dialog__body {
    padding: 16px;
  }
}

:deep .check-color {
  .el-dialog__body {
    background: #fdfdff;
  }
}

:deep(.card-box) {
  .add {
    background: none;
    padding: 0;
  }
}
:deep .el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  border: unset !important;
}
:deep .el-table td.el-table__cell {
  border: unset !important;
}
:deep .el-table.el-table--small {
  border: unset !important;
}

:deep .el-dialog .el-dialog__header {
  background: #fff;
  border-bottom: 1px solid #ebeef5;
}
:deep .el-table::before {
  display: none;
}
:deep .el-table__fixed-right::before {
  display: none;
}
</style>
